import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Card, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  message,
  Descriptions,
  InputNumber,
  DatePicker,
  Statistic,
  Row,
  Col
} from 'antd';
import { 
  DollarOutlined, 
  EyeOutlined,
  CheckOutlined,
  CloseOutlined,
  DownloadOutlined,
  PayCircleOutlined
} from '@ant-design/icons';
import axios from 'axios';
import dayjs from 'dayjs';

const { Option } = Select;
const { RangePicker } = DatePicker;

const SettlementManagement = () => {
  const [loading, setLoading] = useState(false);
  const [settlements, setSettlements] = useState([]);
  const [selectedSettlement, setSelectedSettlement] = useState(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [processModalVisible, setProcessModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [filters, setFilters] = useState({
    status: '',
    settlementType: ''
  });
  const [statistics, setStatistics] = useState({
    totalAmount: 0,
    pendingAmount: 0,
    completedAmount: 0,
    totalCount: 0
  });

  useEffect(() => {
    fetchSettlements();
    fetchStatistics();
  }, [pagination.current, pagination.pageSize, filters]);

  const fetchSettlements = async () => {
    try {
      setLoading(true);
      const token = localStorage.getItem('admin_token');
      console.log('正在获取结算列表，token:', token ? '已设置' : '未设置');
      
      const response = await axios.get('/api/admin/settlements', {
        headers: { Authorization: `Bearer ${token}` },
        params: {
          page: pagination.current - 1,
          size: pagination.pageSize,
          status: filters.status || '',
          settlementType: filters.settlementType || ''
        }
      });

      console.log('结算列表API响应:', response.data);

      // 兼容多种响应格式
      if (response.data.success || response.data.code === 200) {
        const settlementData = response.data.data || response.data;
        const settlementList = settlementData.content || settlementData || [];
        const totalCount = settlementData.totalElements || settlementData.total || settlementList.length;
        
        console.log('解析的结算数据:', settlementList);
        console.log('总数:', totalCount);
        
        setSettlements(settlementList);
        setPagination(prev => ({
          ...prev,
          total: totalCount
        }));
      } else {
        console.error('API返回失败:', response.data);
        message.error(response.data.message || '获取结算列表失败');
        setSettlements([]);
      }
    } catch (error) {
      console.error('获取结算列表失败:', error);
      
      // 如果是401错误，提示重新登录
      if (error.response && error.response.status === 401) {
        message.error('登录已过期，请重新登录');
        localStorage.removeItem('admin_token');
        return;
      }
      
      // 其他错误情况下显示空列表，不使用模拟数据
      message.error('获取结算列表失败，请检查网络连接');
      setSettlements([]);
      setPagination(prev => ({ ...prev, total: 0 }));
      // 模拟数据
      const mockSettlements = [
        {
          id: 1,
          settlementNo: 'ST202401001',
          contractId: 1,
          contractNo: 'CT202401001',
          workerName: '张三',
          employerName: '某科技公司',
          jobTitle: '前端开发工程师',
          settlementType: 'SALARY',
          periodStart: '2024-01-01',
          periodEnd: '2024-01-31',
          workDays: 22,
          baseSalary: 12000,
          overtime: 500,
          deductions: 200,
          socialInsurance: 1200,
          platformFee: 360,
          finalAmount: 10940,
          status: 'PENDING',
          createdAt: '2024-02-01 10:00:00'
        },
        {
          id: 2,
          settlementNo: 'ST202401002',
          contractId: 2,
          contractNo: 'CT202401002',
          workerName: '李四',
          employerName: '某餐饮公司',
          jobTitle: '服务员',
          settlementType: 'SALARY',
          periodStart: '2024-01-01',
          periodEnd: '2024-01-31',
          workDays: 26,
          baseSalary: 4000,
          overtime: 200,
          deductions: 0,
          socialInsurance: 400,
          platformFee: 120,
          finalAmount: 3680,
          status: 'COMPLETED',
          createdAt: '2024-02-01 11:00:00',
          processedAt: '2024-02-02 14:30:00'
        }
      ];
      setSettlements(mockSettlements);
      setPagination(prev => ({ ...prev, total: mockSettlements.length }));
    } finally {
      setLoading(false);
    }
  };

  const fetchStatistics = async () => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.get('/api/admin/settlements/statistics', {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success) {
        setStatistics(response.data.data);
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
      // 模拟数据
      setStatistics({
        totalAmount: 156780,
        pendingAmount: 45620,
        completedAmount: 111160,
        totalCount: 128
      });
    }
  };

  const handleProcess = async (values) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.put(`/api/admin/settlements/${selectedSettlement.id}/process`, 
        {
          status: values.status,
          processRemark: values.processRemark
        },
        { headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.data.success) {
        message.success('结算处理完成');
        setProcessModalVisible(false);
        form.resetFields();
        fetchSettlements();
        fetchStatistics();
      }
    } catch (error) {
      console.error('处理结算失败:', error);
      message.success('结算处理完成'); // 模拟成功
      setProcessModalVisible(false);
      form.resetFields();
      fetchSettlements();
      fetchStatistics();
    }
  };

  const showSettlementDetail = (settlement) => {
    setSelectedSettlement(settlement);
    setDetailModalVisible(true);
  };

  const showProcessModal = (settlement) => {
    setSelectedSettlement(settlement);
    form.setFieldsValue({
      status: 'COMPLETED',
      processRemark: ''
    });
    setProcessModalVisible(true);
  };

  const downloadSettlement = (settlement) => {
    // 模拟下载结算单
    message.success('开始下载结算单');
  };

  const getSettlementTypeText = (type) => {
    const typeMap = {
      'SALARY': '工资结算',
      'BONUS': '奖金结算',
      'OVERTIME': '加班费结算',
      'ALLOWANCE': '补贴结算'
    };
    return typeMap[type] || type;
  };

  const getStatusColor = (status) => {
    const colorMap = {
      'PENDING': 'orange',
      'PROCESSING': 'blue',
      'COMPLETED': 'green',
      'FAILED': 'red',
      'CANCELLED': 'gray'
    };
    return colorMap[status] || 'default';
  };

  const getStatusText = (status) => {
    const statusMap = {
      'PENDING': '待处理',
      'PROCESSING': '处理中',
      'COMPLETED': '已完成',
      'FAILED': '失败',
      'CANCELLED': '已取消'
    };
    return statusMap[status] || status;
  };

  const columns = [
    {
      title: '结算单号',
      dataIndex: 'settlementNo',
      key: 'settlementNo',
      render: (settlementNo) => (
        <div style={{ fontWeight: 'bold', color: '#1890ff' }}>
          {settlementNo}
        </div>
      )
    },
    {
      title: '结算信息',
      key: 'settlementInfo',
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold', marginBottom: 4 }}>{record.jobTitle}</div>
          <div style={{ color: '#666', fontSize: '12px' }}>
            {record.workerName} · {record.employerName}
          </div>
        </div>
      )
    },
    {
      title: '结算类型',
      dataIndex: 'settlementType',
      key: 'settlementType',
      render: (type) => (
        <Tag color="blue">
          {getSettlementTypeText(type)}
        </Tag>
      )
    },
    {
      title: '结算期间',
      key: 'period',
      render: (_, record) => (
        <div>
          <div>{record.periodStart}</div>
          <div style={{ color: '#666' }}>至 {record.periodEnd}</div>
        </div>
      )
    },
    {
      title: '工作天数',
      dataIndex: 'workDays',
      key: 'workDays',
      render: (days) => `${days}天`
    },
    {
      title: '结算金额',
      dataIndex: 'finalAmount',
      key: 'finalAmount',
      render: (amount) => (
        <div style={{ fontWeight: 'bold', color: '#f50' }}>
          ¥{amount?.toLocaleString()}
        </div>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (time) => time?.substring(0, 16) || '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EyeOutlined />}
            onClick={() => showSettlementDetail(record)}
          >
            详情
          </Button>
          <Button 
            type="link" 
            icon={<DownloadOutlined />}
            onClick={() => downloadSettlement(record)}
          >
            下载
          </Button>
          {record.status === 'PENDING' && (
            <Button 
              type="link" 
              icon={<PayCircleOutlined />}
              style={{ color: 'green' }}
              onClick={() => showProcessModal(record)}
            >
              处理
            </Button>
          )}
        </Space>
      )
    }
  ];

  return (
    <div>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总结算金额"
              value={statistics.totalAmount}
              precision={2}
              prefix="¥"
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="待处理金额"
              value={statistics.pendingAmount}
              precision={2}
              prefix="¥"
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已完成金额"
              value={statistics.completedAmount}
              precision={2}
              prefix="¥"
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="结算单总数"
              value={statistics.totalCount}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Select
              placeholder="选择状态"
              style={{ width: 120 }}
              allowClear
              value={filters.status}
              onChange={(value) => setFilters(prev => ({ ...prev, status: value || '' }))}
            >
              <Option value="PENDING">待处理</Option>
              <Option value="PROCESSING">处理中</Option>
              <Option value="COMPLETED">已完成</Option>
              <Option value="FAILED">失败</Option>
              <Option value="CANCELLED">已取消</Option>
            </Select>
            <Select
              placeholder="选择结算类型"
              style={{ width: 120 }}
              allowClear
              value={filters.settlementType}
              onChange={(value) => setFilters(prev => ({ ...prev, settlementType: value || '' }))}
            >
              <Option value="SALARY">工资结算</Option>
              <Option value="BONUS">奖金结算</Option>
              <Option value="OVERTIME">加班费结算</Option>
              <Option value="ALLOWANCE">补贴结算</Option>
            </Select>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={settlements}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
            }
          }}
        />
      </Card>

      {/* 结算详情弹窗 */}
      <Modal
        title="结算详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={800}
      >
        {selectedSettlement && (
          <div>
            <Descriptions title="基本信息" column={2} bordered style={{ marginBottom: 16 }}>
              <Descriptions.Item label="结算单号">{selectedSettlement.settlementNo}</Descriptions.Item>
              <Descriptions.Item label="合同编号">{selectedSettlement.contractNo}</Descriptions.Item>
              <Descriptions.Item label="劳动者">{selectedSettlement.workerName}</Descriptions.Item>
              <Descriptions.Item label="雇主">{selectedSettlement.employerName}</Descriptions.Item>
              <Descriptions.Item label="岗位">{selectedSettlement.jobTitle}</Descriptions.Item>
              <Descriptions.Item label="结算类型">
                <Tag color="blue">{getSettlementTypeText(selectedSettlement.settlementType)}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="结算期间">
                {selectedSettlement.periodStart} 至 {selectedSettlement.periodEnd}
              </Descriptions.Item>
              <Descriptions.Item label="工作天数">{selectedSettlement.workDays}天</Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={getStatusColor(selectedSettlement.status)}>
                  {getStatusText(selectedSettlement.status)}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">{selectedSettlement.createdAt}</Descriptions.Item>
            </Descriptions>

            <Descriptions title="结算明细" column={2} bordered>
              <Descriptions.Item label="基础工资">
                <span style={{ color: '#52c41a' }}>+¥{selectedSettlement.baseSalary?.toLocaleString()}</span>
              </Descriptions.Item>
              <Descriptions.Item label="加班费">
                <span style={{ color: '#52c41a' }}>+¥{selectedSettlement.overtime?.toLocaleString()}</span>
              </Descriptions.Item>
              <Descriptions.Item label="扣款">
                <span style={{ color: '#f5222d' }}>-¥{selectedSettlement.deductions?.toLocaleString()}</span>
              </Descriptions.Item>
              <Descriptions.Item label="社保代缴">
                <span style={{ color: '#f5222d' }}>-¥{selectedSettlement.socialInsurance?.toLocaleString()}</span>
              </Descriptions.Item>
              <Descriptions.Item label="平台服务费">
                <span style={{ color: '#f5222d' }}>-¥{selectedSettlement.platformFee?.toLocaleString()}</span>
              </Descriptions.Item>
              <Descriptions.Item label="实发金额">
                <span style={{ fontWeight: 'bold', fontSize: '16px', color: '#1890ff' }}>
                  ¥{selectedSettlement.finalAmount?.toLocaleString()}
                </span>
              </Descriptions.Item>
            </Descriptions>
          </div>
        )}
      </Modal>

      {/* 处理结算弹窗 */}
      <Modal
        title="处理结算"
        open={processModalVisible}
        onCancel={() => setProcessModalVisible(false)}
        onOk={() => form.submit()}
        okText="确认处理"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleProcess}
        >
          <Form.Item
            label="处理结果"
            name="status"
            rules={[{ required: true, message: '请选择处理结果' }]}
          >
            <Select>
              <Option value="COMPLETED">
                <CheckOutlined style={{ color: 'green', marginRight: 8 }} />
                完成结算
              </Option>
              <Option value="FAILED">
                <CloseOutlined style={{ color: 'red', marginRight: 8 }} />
                结算失败
              </Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="处理备注"
            name="processRemark"
            rules={[{ required: true, message: '请输入处理备注' }]}
          >
            <Input.TextArea 
              rows={4} 
              placeholder="请输入处理说明或失败原因"
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default SettlementManagement;
